/**
 * 
 */
package com.chengyu.eyc.controller;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.chengyu.eyc.base.ResponseResult;
import com.chengyu.eyc.enums.PublishInfoStatusEnum;
import com.chengyu.eyc.model.EycPublicInfo;
import com.chengyu.eyc.properties.EycProperties;
import com.chengyu.eyc.service.EycBaseService;
import com.chengyu.eyc.utils.EycFileUtil;

/**
 * @author kevin
 *
 */
@RequestMapping("file")
@RestController
public class FileController extends AbstractBaseController{
    
    @Autowired
    EycProperties eycProperties;
    
    @Autowired
    EycBaseService eycBaseService;
    
    @GetMapping("getFile")
    public ResponseEntity<FileSystemResource> getFile(@RequestParam("filePath") String filePath, @RequestParam("fileNme") String fileNme) {
        String fileDir=eycProperties.getFileDir();
        File file = new File(filePath.startsWith("/")? fileDir+ filePath:fileDir+File.separator+filePath, fileNme);
        return EycFileUtil.getResponseResource(file);
    }
    
    @PostMapping("uploadFile")
    public ResponseResult<EycPublicInfo> uploadFile(@RequestParam(value = "file") MultipartFile file,
        EycPublicInfo eycPublicInfo) throws IOException {
        String fileNme = EycFileUtil.uploadFile(this.eycProperties.getFileDir() +File.separator+ eycPublicInfo.getPageCde(), file);
        String filePath=eycProperties.getDomainName()+"/file/getFile?filePath=%s&fileNme=%s";
        eycPublicInfo.setPictureUrl(String.format(filePath,eycPublicInfo.getPageCde(), fileNme)); 
        eycPublicInfo.setStatus(PublishInfoStatusEnum.DRAFT.getCode());
        return ResponseResult.ok(eycBaseService.insertEycPublicInfo(eycPublicInfo));
    }

}
